#include "VideoWidget.h"
#include <QPainter>
#include <QDebug>


VideoWidget::VideoWidget(QWidget *parent)
    : QWidget(parent)
{
     // 设置背景为黑色
     setStyleSheet("background-color: black;");
    
     // 设置最小尺寸
     setMinimumSize(320, 240);
     
     qDebug() << "[VideoWidget] 创建视频组件";
}

VideoWidget::~VideoWidget()
{
    qDebug() << "[VideoWidget] 销毁视频窗口";
}

void VideoWidget::updateImage(const QImage& image,int64_t ptsMs)
{
    QMutexLocker locker(&m_frameMutex);

    m_currentImage=image;
    update();
}


void VideoWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    
    QPainter painter(this);
    
    QMutexLocker locker(&m_frameMutex);
    
    if (m_currentImage.isNull()) {
        // 没有帧时，显示黑色背景 + 提示文字
        painter.fillRect(rect(), Qt::black);
        painter.setPen(Qt::white);
        painter.drawText(rect(), Qt::AlignCenter, "等待视频...");
        return;
    }
    
    // 计算缩放后的矩形（保持宽高比）
    QSize imageSize = m_currentImage.size();
    QSize widgetSize = size();
    
    // 计算缩放比例（保持宽高比，填充窗口）
    double widthRatio = static_cast<double>(widgetSize.width()) / imageSize.width();
    double heightRatio = static_cast<double>(widgetSize.height()) / imageSize.height();
    double ratio = qMin(widthRatio, heightRatio);  // 选择较小的比例，确保完全显示
    
    // 计算缩放后的尺寸
    int scaledWidth = static_cast<int>(imageSize.width() * ratio);
    int scaledHeight = static_cast<int>(imageSize.height() * ratio);
    
    // 居中显示
    int x = (widgetSize.width() - scaledWidth) / 2;
    int y = (widgetSize.height() - scaledHeight) / 2;
    
    // 绘制黑色背景
    painter.fillRect(rect(), Qt::black);
    
    // 绘制缩放后的图像
    QRect targetRect(x, y, scaledWidth, scaledHeight);
    painter.drawImage(targetRect, m_currentImage);
}